package com.makemoney.miniprogram.security.config;

import com.makemoney.miniprogram.security.component.*;
import com.makemoney.miniprogram.security.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.vote.AffirmativeBased;
import org.springframework.security.access.vote.AuthenticatedVoter;
import org.springframework.security.access.vote.RoleVoter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

import java.util.Arrays;

/**
 * Spring Security 配置类，将所有要用到的组件统一配置到这里，以免出现循环依赖等问题。
 */
@Configuration
public class CommonSecurityConfig {
    /**
     * 密码强度 4-16 数越大速度越慢
     */
    @Value("${secure.encode.strength}")
    private Integer strength;
    // 注册白名单 Bean
    @Bean
    public IgnoreUrlsConfig ignoreUrlsConfig(){
        return  new IgnoreUrlsConfig();
    }

    // 注册 JWT 工具类 Bean
    @Bean
    public JwtTokenUtil jwtTokenUtil(){
        return new JwtTokenUtil();
    }

    // 注册自定义认证失败逻辑 Bean
    @Bean
    public RestAuthenticationEntryPoint restAuthenticationEntryPoint(){
        return new RestAuthenticationEntryPoint();
    }

    // 注册自定义权限不足处理 Bean
    @Bean
    public RestfulAccessDeniedHandler restfulAccessDeniedHandler(){
        return new RestfulAccessDeniedHandler();
    }

    // 注册 JWT 登录授权过滤器 Bean
    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){
        return new JwtAuthenticationTokenFilter();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder(strength);
    }


    @Bean
    public FilterInvocationSecurityMetadataSource securityMetadataSource() {
        return new CustomSecurityMetadataSource();
    }
}

